package com.raven.craft.code.generator.mysql.schema.excel;

import com.raven.craft.code.generator.IGenerator;
import com.raven.craft.code.generator.common.constant.FileSuffix;
import com.raven.craft.code.generator.common.file.ExcelFile;
import com.raven.craft.code.generator.common.file.metadata.FileMetadata;
import com.raven.craft.code.generator.config.MysqlContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

import java.util.List;

/**
 * @author raven
 * @date 2020/08/25
 **/
@Slf4j
public class ExcelSchemaGenerator implements IGenerator {

    private final MysqlContext context;
    private final ExcelSchemaProperties properties;

    public ExcelSchemaGenerator(MysqlContext context, ExcelSchemaProperties properties) {
        this.context = context;
        this.properties = properties;
    }

    public static ExcelFile createExcelFile(MysqlContext context, ExcelSchemaProperties properties) {
        FileMetadata metadata = new FileMetadata(context.getDatabase(), FileSuffix.XLSX, properties.getTargetDir());
        ExcelSchemaVo vo = new ExcelSchemaVo(context, properties);
        Workbook workbook = createWorkbook(vo);
        return new ExcelFile(metadata, workbook);
    }

    private static Workbook createWorkbook(ExcelSchemaVo excelSchemaVo) {
        SXSSFWorkbook workbook = new SXSSFWorkbook();
        excelSchemaVo.getSections().forEach(section -> {
            SXSSFSheet sheet = workbook.createSheet(section.getName());
            appendRow(sheet, excelSchemaVo.getSchemaTitles());
            section.getRows().forEach(row -> {
                appendRow(sheet, row);
            });
        });
        return workbook;
    }

    private static void appendRow(Sheet sheet, List<String> data) {
        int newRowNum = sheet.getLastRowNum() + 1;
        Row row = sheet.createRow(newRowNum);

        for (int i = 0; i < data.size(); i++) {
            Cell cell = row.createCell(i);
            cell.setCellValue(data.get(i));
        }
    }

    @Override
    public void generate() {
        log.info("begin to generate excel schema file");
        createExcelFile(context, properties).output();
    }

}
